﻿$(document).ready(function () {
	$('input[name^="PurchaseLogItems["][name$=".Quantity"]').on('change', CalculateRowValues);
	$('input[name^="PurchaseLogItems["][name$=".Price"]').on('change', CalculateRowValues);
	$('select[name^="PurchaseLogItems["][name$=".ProductId"]').on('change', GetProductDetails);
});

function GetGuidFromName(name) {
	var start = name.indexOf("[") + 1;
	var end = name.indexOf("]");
	return name.substring(start, end);
}

var viewModel = {
	// function adds the new row to the html
	AddNewItem: function () {
		// generate a Guid value used to make the ID and NAME attributes unique for this row
		var guid = viewModel._generateGuid();
		// using JSRENDER we get the template from the itemTemplate script object and replace all "index" with the guid value
		var html = $("#itemTemplate").render({ "index": guid });
		$("#tableItems").append(html);

		var quantity = 'input[name="PurchaseLogItems[' + guid + '].Quantity"]';
		var price = 'input[name="PurchaseLogItems[' + guid + '].Price"]';
		var productList = 'select[name="PurchaseLogItems[' + guid + '].ProductId"]';

		$(quantity).on('change', CalculateRowValues);
		$(price).on('change', CalculateRowValues);
		$(productList).on('change', GetProductDetails);
		//if ($("#IsCreate").val() == "False") {
		//}
		//else {
		//}
	},

	// generates a unique GUID
	_generateGuid: function () {
		// Source: http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/105074#105074
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
			var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
			return v.toString(16);
		});
	}
};

function GetProductDetails() {
	// this.name - "PurchaseLogItems[ff04985b-b7ab-45b2-90ad-d80e382caa82].Id"
	var guid = GetGuidFromName(this.name);
	var productSelectList = 'select[name="' + this.name + '"]';
	var productSelectListValue = $(productSelectList).val();

	// check if a value has been selected (do not send request for the 'select one' option)
	if (productSelectListValue) {
		var dataObject = {
			id: $(productSelectList).val()
		};

		var jsonSerializedEntity = JSON.stringify(dataObject);
		$.ajax({
			type: "POST",
			url: "/Product/DetailsJson",
			dataType: "json",
			contentType: "application/json; charset=utf-8",
			data: jsonSerializedEntity,
			success: function(result) {
				console.log(result);
				if (result[0] == "success") {
					var product = result[1];
					SetRowValues(guid, false, product.Id, product.CategoryId, product.Amount, product.AmountUnitId, product.QuantityUnitId, product.ProductManufacturerId, product.ProductAmountUnit != null ? product.ProductAmountUnit.Name : "", product.ProductQuantityUnit != null ? product.ProductQuantityUnit.Name : "", product.Name, product.Quantity)
				} else {
					SetRowValues(guid, true);
				}
			},
			error: function(error) {
				console.log("There was an error posting the data to the server: " + error.responseText);
				SetRowValues(guid, true);
			}
		});
	} else {
		SetRowValues(guid, true);
	}
}

function CalculateRowValues() {
	// this.name - "PurchaseLogItems[ff04985b-b7ab-45b2-90ad-d80e382caa82].Id"
	var guid = GetGuidFromName(this.name);

	var $quantity = $('input[name="PurchaseLogItems[' + guid + '].Quantity"]');
	var $price = $("input[name='PurchaseLogItems[" + guid + "].Price']");
	var quantityValue = parseFloat($quantity.val());
	var priceValue = parseFloat($price.val());

	// make sure all values are populated
	if (!isNaN(quantityValue) && !isNaN(priceValue)) {
		if (quantityValue > 0 && priceValue > 0) {
			var $pricePerItem = $('input[name="PurchaseLogItems[' + guid + '].PricePerItem"]');
			var $productAmount = $('input[name="PurchaseLogItems[' + guid + '].Product.Amount"]');
			var $pricePerAmountUnit = $('input[name="PurchaseLogItems[' + guid + '].PricePerAmountUnit"]');
			var $quantityProduct = $('input[name="PurchaseLogItems[' + guid + '].Quantity"]');
			var $pricePerQuantityUnit = $('input[name="PurchaseLogItems[' + guid + '].PricePerQuantityUnit"]');

			var amountProductValue = parseFloat($productAmount.val());
			var quantityProductValue = parseFloat($quantityProduct.val());

			var pricePeritemValue = quantityValue == 1 ? priceValue : priceValue / quantityValue;
			var pricePerAmountUnitValue = isNaN(amountProductValue) ? 0 : priceValue / amountProductValue;
			var pricePerQuantityUnitValue = isNaN(quantityProductValue) ? 0 : priceValue / quantityProductValue;

			$pricePerItem.val(pricePeritemValue.toFixed(2));
			$pricePerAmountUnit.val(pricePerAmountUnitValue.toFixed(3));
			$pricePerQuantityUnit.val(pricePerQuantityUnitValue.toFixed(3));

			CalculateTotalPrice();
		}
	}
}

function CalculateTotalPrice() {
	var sum = 0;
	$.each($('input[name^="PurchaseLogItems["][name$=".Price"]'), function (index, value) { sum += parseFloat(value.value); });
	$("#TotalCost").val(sum.toFixed(3));
}

function SetRowValues(guid, isError, productId, categoryId, amountValue, amountUnitId, quantityUnitId, productManufacturerId, productAmountUnitName, productQuantityUnitName, productName, productQuantity) {
	// hidden inputs
	var $productId = $('input[name="PurchaseLogItems[' + guid + '].Product.Id"]');
	var $productCategoryId = $('input[name="PurchaseLogItems[' + guid + '].Product.CategoryId"]');
	var $productAmount = $('input[name="PurchaseLogItems[' + guid + '].Product.Amount"]');
	var $productAmountUnitId = $('input[name="PurchaseLogItems[' + guid + '].Product.AmountUnitId"]');
	var $productQuantityUnitId = $('input[name="PurchaseLogItems[' + guid + '].Product.QuantityUnitId"]');
	var $productManufacturerId = $('input[name="PurchaseLogItems[' + guid + '].Product.ProductManufacturerId"]');
	var $productName = $('input[name="PurchaseLogItems[' + guid + '].Product.Name"]');
	var $productQuantity = $('input[name="PurchaseLogItems[' + guid + '].Product.Quantity"]');
	
	// these are spans so the ID attribute of the span is used
	var $productAmountUnitName = $('#PurchaseLogItems_' + guid + '__Product_ProductAmountUnit_Name');
	var $productQuantityUnitName = $('#PurchaseLogItems_' + guid + '__Product_ProductQuantityUnit_Name');
	
	if (!isError) {
		$productId.val(productId);
		$productCategoryId.val(categoryId);
		$productAmount.val(amountValue);
		$productAmountUnitId.val(amountUnitId);
		$productQuantityUnitId.val(quantityUnitId);
		$productManufacturerId.val(productManufacturerId);
		$productName.val(productName);
		$productQuantity.val(productQuantity);
		
		// set the text of the span
		$productAmountUnitName.text(productAmountUnitName);
		$productQuantityUnitName.text(productQuantityUnitName);
	} else {
		$productId.val("");
		$productCategoryId.val("");
		$productAmount.val("");
		$productAmountUnitId.val("");
		$productQuantityUnitId.val("");
		$productManufacturerId.val("");
		$productName.val("");
		$productQuantity.val("");
		
		// set the text of the span
		$productAmountUnitName.text("per item");
		$productQuantityUnitName.text("per #");
	}
}

